package cn.tedu.ivoscm.vehicle.service.impl;

import cn.tedu.ivoscm.base.exception.ServiceException;
import cn.tedu.ivoscm.base.response.StatusCode;
import cn.tedu.ivoscm.vehicle.mapper.VehicleMapper;
import cn.tedu.ivoscm.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivoscm.vehicle.pojo.dto.VehicleSaveParam;
import cn.tedu.ivoscm.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivoscm.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivoscm.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public List<VehicleVO> select(VehicleQuery vq) {
        log.debug("查询车辆列表业务：{}", vq);
        List<VehicleVO> list = vehicleMapper.select(vq);
        return list;
    }

    @Override
    public void save(VehicleSaveParam vsp) {
        log.debug("保存车辆信息业务：{}", vsp);
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vsp, vehicle);
        VehicleQuery vq = new VehicleQuery();
        vq.setLicense(vehicle.getLicense());
        vq.setCode(vehicle.getCode());
        List<VehicleVO> list = vehicleMapper.select(vq);
        if (!list.isEmpty()) {
            throw new ServiceException(StatusCode.DATA_EXISTS);
        }
        if (vehicle.getId() == null) {
            vehicle.setCreateTime(new Date());
            vehicle.setGeofenceBindStatus("0");
            vehicle.setStatus("1");
            vehicleMapper.insert(vehicle);
        } else {
            vehicle.setUpdateTime(new Date());
            vehicleMapper.update(vehicle);
        }
    }

    @Override
    public void unbind(Long id) {
        log.debug("解除车辆围栏绑定业务，{}", id);
        Vehicle v = new Vehicle();
        v.setId(id);
        v.setUpdateTime(new Date());
        v.setGeofenceBindStatus("0");
        v.setGeofenceId(null);
        vehicleMapper.unbind(v);
    }

    @Override
    public void bind(Long vid, Long gid) {
        log.debug("设置车辆围栏绑定业务：车辆id {}, 围栏id {}", vid, gid);
        Vehicle v = new Vehicle();
        v.setId(vid);
        v.setUpdateTime(new Date());
        v.setGeofenceBindStatus("1");
        v.setGeofenceId(gid);
        vehicleMapper.bind(v);
    }

    @Override
    public void unbindAllThisGid(Long gid) {
        log.debug("解除车辆围栏绑定业务，{}", gid);
        Vehicle v = new Vehicle();
        v.setUpdateTime(new Date());
        v.setGeofenceId(gid);
        vehicleMapper.unbindAllThisGid(v);
    }

    @Override
    public void deleteById(Long id) {
        log.debug("删除车辆信息业务：{}", id);
        vehicleMapper.deleteById(id);
    }
}
